package com.platform.rbac.example.controller;

import cn.hutool.core.util.StrUtil;
import com.platform.rbac.exception.TokenAutheFailException;
import com.platform.rbac.jwt.JWTUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class BaseController {

    protected User getUser(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("token");
        if (StrUtil.isNotEmpty(token)) {
            //验证token是否有效
            String username = JWTUtil.getUsername(token);
            if (StrUtil.isNotEmpty(username)){
                boolean verify = JWTUtil.verify(token, username);
                if (verify){
                    //从数据库 或者 redis中获取用户信息
                    return new User();
                }
            }
        }
        throw new TokenAutheFailException("身份验证失败，请重新登录");
    }

}
class User{
    private String username;
    private String tell;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getTell() {
        return tell;
    }

    public void setTell(String tell) {
        this.tell = tell;
    }
}
